package com.ltmonitor.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.Department;
import com.ltmonitor.entity.TenantEntity;
import com.ltmonitor.entity.UserInfo;
import com.ltmonitor.service.IDepartmentService;
import com.ltmonitor.service.IUserInfoService;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;
import com.ltmonitor.web.vo.TreeNode;

@Controller
@RequestMapping("/dep")
public class DepartmentAction extends PaginateAction {

	public static String TREE_VEHICLE_GROUP = "vehicleGroup";
	public static String TREE_ORGANIZATION = "organization";
	
	@Autowired
	private IUserInfoService userInfoService;
	

	@RequestMapping("/viewList.action")
	public String list()
	{
		return "/department/depList";
	}
	@RequestMapping("/view.action")
	public String view(Model m,
			@RequestParam(value = "entityId", required = false, defaultValue="0") long id) {
		try {
			if (id > 0) {
				Department dep = this.departmentService.load(id);
				m.addAttribute("entity", dep);
			}else
			{
				Department d = new Department();
				m.addAttribute("entity", d);				
			}
			//m.addObject("message", "保存成功");

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message","发生错误:"+ex.getMessage());
		}
		return "/department/editDep";		
	}
	/**
	 * 打开选择部门的页面，此此页面提供查询部门，并提供选择部门的功能
	 * @param m
	 * @param id
	 * @return
	 */
	@RequestMapping("/viewSelectDep.action")
	public String viewSelectDep(Model m) {
		
		return "/department/selectDepartment";		
	}
	/**
	 * 新增部门修改或新增后提交系统保存
	 */
	@RequestMapping("/save.action")
	public String save(Model m,Department dep) {
		try {
			long depId = dep.getEntityId();
			if (depId > 0) {
				//避免无限递归
				if (depId == dep.getParentId()) {
					m.addAttribute("message","保存错误:上级车组不能是本车组!");
					return SAVE_SUCCESS;
				}

				List<Long> childDepIdList = this.departmentService
						.getDepIdList(depId);
				if (childDepIdList.contains(dep.getParentId())) {
					m.addAttribute("message","上级车组不能同时是本车组的下级车组!");
					return SAVE_SUCCESS;
				}
			}
			// this.save();
			departmentService.saveDepartment(dep);
			
			/**
			 * 如果用户拥有新增的部门的上级部门的权限，将自动拥有新增部门的权限
			 */
			if (depId == 0) {
				userInfoService.assignDepartmentToUser(dep, this.getOnlineUser().getEntityId());
			}
			UserInfo u = (UserInfo) this.userInfoService.load(this.getOnlineUser().getEntityId());
			super.setAuthorizedDep(u);

			m.addAttribute("message","保存成功");
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message",ex.getMessage());
		}

		m.addAttribute("entity", dep);				
		return "/department/editDep";
	}
	/**
	 * 假删除
	 * @param entityId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/fakeDelete.action")
	public JsonMessage fakeDelete(long entityId) {
		long depId = entityId;
		try {
			String hql = "from VehicleData where depId = ? and deleted = ?";
			Object obj = this.vehicleDataService.find(hql,
					new Object[] { depId, false });
			if (obj != null) {
				return super.json(false, "该车组下分配有车辆，不能删除!");
			}
			hql = "from Department where parentId = ? and deleted = ?";
			obj = this.departmentService.find(hql, new Object[] { depId, false });
			if (obj != null) {
				return super.json(false, "该车组下有子部门，不能删除!");
			}

			departmentService.deleteFakeById(depId);
			return super.json(true, "记录已被成功刪除!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}
	}

	/**
	 *  加载部门数据列表，在前端形成树状菜单
	 * @param userId
	 * @return
	 */

	@ResponseBody
	@RequestMapping("/menu.action")
	public List<TreeNode> menu(@RequestParam(defaultValue="0") long userId, @RequestParam(defaultValue="0") long depId, String treeType) {
		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		try {
			
			String hql = "from Department where deleted = ?";
			List depList = null;
			if (super.getOnlineUser().isSuperAdmin() && depId == 0 ) {
				depList = this.departmentService.query(hql, false);
			} else {
				List<Long> depIdList = null;
				if (TREE_ORGANIZATION.equals(treeType)) {
					depIdList = this.departmentService.getDepIdList(this.getOnlineUser().getCompanyId());//用户所属的企业/部门的管理权限
				} else {	
					if(depId > 0)
					{
						depIdList = this.departmentService.getDepIdList(depId);
					}else
					{
						depIdList = this.getAuthorizedDepIdList();		//系统分配的可以监控的车组权限	
					}
				}

				depList = new ArrayList<Department>();
				for (long id : depIdList) {
					Department dep = departmentService.fetchDepartment(id);
					if (dep.getDeleted() == false)
						depList.add(dep);
				}
			}

			Map<String, TreeNode> nodeMap = new HashMap<String, TreeNode>();
			for (Object obj : depList) {
				Department bd = (Department) obj;
				String parentId = bd.getParentId() == 0 ? null : ("" + bd
						.getParentId());
				TreeNode node = new TreeNode("" + bd.getEntityId(),
						bd.getName(), parentId, "icon-polygon");
				node.setState("open");
				node.setLeaf(true);
				nodeMap.put(node.getId(), node);
			}

			// 判断是否选中
			if (userId > 0) {
				List<Department> deps = this.departmentService.getDepartmentListByUserId(userId);
				for (Department dep : deps) {
					String nodeId = "" + dep.getEntityId();
					TreeNode node = nodeMap.get(nodeId);
					if (node != null) {
						node.setChecked(true);
					}
				}
			}
			TreeNode rootNode = new TreeNode("0", "请选择车组", "0", "icon-polygon");
			rootNode.setState("open");
			nodeList.add(rootNode);
			for (TreeNode node : nodeMap.values()) {
				if (node.getPid() != null) {
					TreeNode parentNode = nodeMap.get(node.getPid());
					if (parentNode != null) {
						parentNode.getChildren().add(node);
						parentNode.setLeaf(false);
						parentNode.setState("closed");
					} else
						rootNode.getChildren().add(node);
				} else
					rootNode.getChildren().add(node);
			}
			//Date end = new Date();
			//double sec = DateUtil.getSeconds(start, end);
			//log.error("deptree cost:"+sec);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			// return json(false, ex.getMessage());
		}
		return nodeList;

	}
	/**
	 * 组织机构下拉树
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/orgTree.action")
	public List<TreeNode> getOrgTree(@RequestParam(defaultValue="0") long userId) {
		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		try {
			//Date start = new Date();
			List<Long> depIdList = this.getAuthorizedDepIdList();

			String hql = "from Department where deleted = ?";
			List depList = null;
			if (super.getOnlineUser().isSuperAdmin()) {
				depList = this.departmentService.query(hql, false);
			} else {
				depList = new ArrayList<Department>();
				for (long depId : depIdList) {
					Department dep = departmentService.fetchDepartment(depId);
					if (dep.getDeleted() == false)
						depList.add(dep);
				}
			}

			Map<String, TreeNode> nodeMap = new HashMap<String, TreeNode>();
			for (Object obj : depList) {
				Department bd = (Department) obj;
				String parentId = bd.getParentId() == 0 ? null : ("" + bd
						.getParentId());
				TreeNode node = new TreeNode("" + bd.getEntityId(),
						bd.getName(), parentId, "icon-polygon");
				node.setState("open");
				node.setLeaf(true);
				nodeMap.put(node.getId(), node);
			}

			// 判断是否选中
			Map checkedDepMap = new HashMap();
			if (userId > 0) {
				//UserInfo u = (UserInfo) this.getBaseService().load(
						//UserInfo.class, userId);
				/**
				 * if (u.getUserFlag() == UserInfo.USER_FLAG_SUPER_ADMIN) {
				 * //超级用户默认全部选中 for (Object depObj : depList) { Department dep =
				 * (Department) depObj; checkedDepMap.put(dep.getEntityId(),
				 * dep); } } else {
				 */
				//Set<Department> deps = u.getDepartments();
				List<Department> deps = this.departmentService.getDepartmentListByUserId(userId);
				for (Department dep : deps) {
					String nodeId = "" + dep.getEntityId();
					TreeNode node = nodeMap.get(nodeId);
					if (node != null) {
						node.setChecked(true);
					}
				}
				// }
			}
			TreeNode rootNode = new TreeNode("0", "请选择车组", "0", "icon-polygon");
			rootNode.setState("open");
			nodeList.add(rootNode);
			for (TreeNode node : nodeMap.values()) {
				if (node.getPid() != null) {
					TreeNode parentNode = nodeMap.get(node.getPid());
					if (parentNode != null) {
						parentNode.getChildren().add(node);
						parentNode.setLeaf(false);
						parentNode.setState("closed");
					} else
						rootNode.getChildren().add(node);
				} else
					rootNode.getChildren().add(node);
			}
			//Date end = new Date();
			//double sec = DateUtil.getSeconds(start, end);
			//log.error("deptree cost:"+sec);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			// return json(false, ex.getMessage());
		}
		return nodeList;

	}




}
